<?php

namespace app\admin\controller\purchase;

use app\common\controller\Backend;
use app\common\model\purchase\ChangeGoods;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Change extends Backend
{
    
    /**
     * Change模型对象
     * @var \app\common\model\purchase\Change
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Change;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['purchaseenter','supplier','storehouse','purchaseorder'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['purchaseenter','supplier','storehouse','purchaseorder'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','collectiontime','explain','operator','company','status','tax']);
                $row->visible(['purchaseenter']);
				$row->getRelation('purchaseenter')->visible(['number']);
				$row->visible(['supplier']);
				$row->getRelation('supplier')->visible(['nickname']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
				$row->visible(['purchaseorder']);
				$row->getRelation('purchaseorder')->visible(['number']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids=null){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);

        if ($this->request->isAjax()) {

            $collectiontime = strtotime(input('collectiontime'));
//            $createtime = strtotime(input('createtime'));

            $explain = input('explain');
            $abstract = input('abstract');

            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            if(!isset($params['crow'])){
                $this->error('未选择换货商品');
            }
            $sdata = $params['row'];
            //检测库存
            $cdata = $params['crow'];


            foreach ($sdata as $k=> $v){
                $ChangeGoods = new ChangeGoods();
                $where = array(
                    'sales_checkout_id' => $ids,
                    'sales_slip_id' => $row['sales_slip_id'],
                );
                $cnum = $ChangeGoods->where($where)->sum('goods_num');//已经换货数量
                $CheckoutGoods = new CheckoutGoods;
                $gnum = $CheckoutGoods->where($where)->sum('goods_num');
                if($v['goods_num']+$cnum >$gnum){
                    $this->error('商品'.$v['goods_id'].'换货超量,已经换货'.$cnum);
                }
            }
            $num = Db::name('sales_change')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                'collectiontime'=>$collectiontime,
                'customer_id'=>$row['customer_id'],
                'storehouse_id'=>$row['customer_id'],
                'explain'=>$explain,
                'abstract'=>$abstract,
                'tax'=>$row['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'sales_slip_id' => $row['sales_slip_id'],
                'operator'=>session('admin')['nickname'],
                'sales_checkout_id' => $ids,
            );
            Db::startTrans();
            try {
                $Change = new \app\admin\controller\sales\Change();
                $Change->save($saledata);
                $gdata = [];

                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'sales_checkout_id' => $ids,
                        'sales_slip_id' => $row['sales_slip_id'],
                        'sales_change_id' => $Change->id,
                    );
                }
                foreach ($cdata as $v){
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'sales_checkout_id' => $ids,
                        'sales_slip_id' => $row['sales_slip_id'],
                        'sales_change_id' => $Change->id,
                        'type'=>2,
                    );
                }
                $ChangeGoods = new ChangeGoods();
                $ChangeGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }
        $list = Db::name('purchase_change_goods')
            ->field('g.id,goods_num,unit_price,tax,remark,title,place_origin,number,unit,specs,sg.type')
            ->alias('sg')
            ->where(array('purchase_change_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
}
